#!/bin/sh
#set -x
[ -z "$butch_do_overwrite_on_copy" ] && butch_do_overwrite_on_copy=false
[ -z "$butch_staging_dir" ] && butch_staging_dir=/opt
[ 1 = $(printf "%s" "$butch_staging_dir" | awk '{n=split($0,a,"/"); print n-1;}') ] || {
	echo "error: butch_staging_dir may contain only one slash"
	echo "good: /opt /pkgs /app"
	echo "bad: /opt/ /var/pkgs /my/apps/"
	exit 1
}


relocate() {
	local dir=$1
	local backlinks=$2
	local do_copy=$3
	mkdir -p "$butch_root"/$dir
	[ -d "$butch_root""$butch_install_dir/$dir" ] || return 0
	cd "$butch_root""$butch_install_dir/$dir" || return 1
	[ -n "$V" ] && echo "relocating $butch_root$butch_install_dir/$dir"
        for i in * ; do
		if [ ! -L "$i" ] && [ -d "$i" ] ; then
			local save="$PWD"
			relocate "$dir/$i" "$backlinks/.." $do_copy
			cd "$save"
		elif [ -f "$i" ] || [ -L "$i" ] ; then
			target="$butch_root/$dir/$i"
			if $do_copy ; then
				if $butch_do_overwrite_on_copy || [ ! -e "$target" ] ; then
					echo cp -a "$butch_root$butch_install_dir/$dir/$i" "$target"
					cp -a "$butch_root$butch_install_dir/$dir/$i" "$target"
				fi
			else
				echo "ln -sf "$backlinks""$butch_install_dir"/"$dir"/"$i" $target"
				ln -sf "$backlinks""$butch_install_dir"/"$dir"/"$i" "$target"
			fi
		else
			[ -n "$V" ] && echo "UNKNOWN object $i"
                fi
	done
	[ -n "$V" ] && echo "relocation done"
}

if [ -z "$1" ] ; then
	echo "tool to manually symlink a built package"
	echo "(i.e. the ones in $butch_staging_dir/packagename)"
	echo "into /"

	echo "error: need to pass package name to relocate" >&2
	exit 1
fi

ec=0

for pkg ; do
	[ "$R" = "/" ] && R=
	butch_root=$R
	butch_install_dir="$butch_staging_dir"/"$pkg"
	if [ -d "$R""$butch_install_dir" ] ; then
		for loc in bin sbin include lib libexec share ; do
			relocate $loc .. false
		done
		for loc in etc var ; do
			relocate $loc .. true
		done
	else
		echo "warning: package $pkg does not seem to be installed" >&2
		ec=1
	fi
done

exit $ec
